using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class app_frame_Default2 : System.Web.UI.Page
{
    //added on 10-Sep-2007
    string strPagesetRowId = "";
    DataSet dseInputInfo = new DataSet();
    DataSet dsePageInfo = new DataSet();
    HtmlForm frmObj;
    string strErrMessage = "";
    security hdds;
    Hashtable sysVar = new Hashtable();

    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString();
        this.Title = "MaxBlox";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.hdds = new security();

        if (!hdds.IsValidPageURL(ref strErrMessage)) // Added by 'Imran Gani' on 19-Jun-2014, for validate URL
        {
            showmessage(strErrMessage);
            return;
        }

        Session["datasort"] = hfSort.Value;

        setRequestURL();//implemented by sanal on 13 Dec 2007

        //Navigator.storeURL(Request.Url.ToString(), IsPostBack, false, false);//implemenetd by sanal on April 03, 2008

        lbl_message.Text = "";
        if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
        if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);
        destroyUnwantedObjects();

        #region Commented by 'Imran Gani' on 19-Jun-2014
        //if (!IsPostBack)
        //{
        //    //mn_main = this.hdds.load_menu(mn_main);
        //    //mn_main.MaximumDynamicDisplayLevels = 10;
        //    //lb_welcome.Text = GlobalValues.Welcome + hdds.hdfu.getUserId();
        //}

        ////Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
        //if (Request.QueryString["mn"] != null)
        //{
        //    if (!hdds.checkObjectMenuAccess(Request.QueryString["mn"]))
        //    {
        //        showmessage();
        //        return;
        //    }
        //}

        ////Code added by Sampath on 15-Nov-2011 for IPP Vertical privilege
        //if (Request.QueryString["PK"] != null && Request.QueryString["pgs_id"] != null)
        //{
        //    if (!hdds.checkRecordAccess(Request.QueryString["PK"].ToString(), Request.QueryString["pgs_id"].ToString()))
        //    {
        //        showmessage();
        //        return;
        //    }
        //}

        //bool blnNoAccess = true;
        //if (Request.QueryString["mn"] != null)
        //{
        //    if (this.hdds.validate_menu(Request.QueryString["mn"].ToString()))
        //    {
        //        blnNoAccess = false;
        //    }
        //}
        //if (blnNoAccess)
        //{
        //    Response.Redirect("Error.aspx");
        //    Response.End();
        //}
        #endregion

        hdds.logMenuClick(Request.QueryString["mn"].ToString());

        if (Request.QueryString["pgs_id"] != null)
        {
            strPagesetRowId = Request.QueryString["pgs_id"];
        }

        if (hihdeletepagesetid.Value != "") // Added by srivatsan to get the child page pagesetid for delete issue
        {
            strPagesetRowId = hihdeletepagesetid.Value;
            hihdeletepagesetid.Value = "";
        }

        Master MA = new Master();
        if (MA.DeleteMessage != "")
        {
            lbl_message.Text = MA.DeleteMessage;
            MA.DeleteMessage = "";
        }
        else
            lbl_message.Text = MA.DeleteMessage;

        if (this.Master.FindControl("Form1") != null) //if (this.FindControl("Form1") != null)
        {
            loadAllVariables();
            //GlobalValues.hsSysVar = sysVar;
            frmObj = (HtmlForm)this.Master.FindControl("Form1");//frmObj = (HtmlForm)this.FindControl("Form1")
            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);

            ////if (Request.QueryString["DPK"] != null) // Commented by srivatsan for delete issue
            ////{
            ////    string strDelKey = Request.QueryString["DPK"].ToString().Replace("'", "''");
            ////    bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
            ////}
            if (hihDeleteClick != null)
            {
                
                //if (!Page.IsPostBack)
                //{
                //    if (Session["DPK"] != null)
                //    {
                //        string strDelKey = Session["DPK"].ToString().Replace("'", "''");
                //        bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
                //        Session["DPK"] = null;
                //    }
                //}

                //else
                //{

                if (hihDeleteClick.Value != "0")
                {
                    if (hihDeleteafrowid.Value != "")
                    {
                        Session["DPK"] = hihDeleteafrowid.Value;
                        if (Session["DPK"] != null)
                        {
                            
                                string strDelKey = Session["DPK"].ToString().Replace("'", "''");
                                bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");

                                if (hihMKafrowid.Value != "")
                                {
                                    Session["MK"] = hihMKafrowid.Value;
                                    if (Session["MK"] != null)
                                    {
                                        if (HttpContext.Current.Request.Url.AbsoluteUri != "")
                                        {
                                            //string previousURL = Navigator.getURL(HttpContext.Current.Request.Url.AbsoluteUri);
                                            Session["MK"] = null;
                                            hihMKafrowid.Value = "";
                                            Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri);
                                        }

                                    }
                                }
                            Session["DPK"] = null;
                        }
                    }
                }
           // }
            }

            DynamicDisplayI DDI = new DynamicDisplayI();
            DDI.Load(strPagesetRowId, frmObj,ref dsePageInfo,null,null);

            if (Request.QueryString["VMODE"] == null) putHeaderButtons(DDI);
            else
            {
                security HDS = new security(); // implemented by Prithi on 4-Nov-08
                bool create = false; bool edit = false; bool delete = false;
                HDS.getPagesetRights(strPagesetRowId, ref create, ref edit, ref delete);

                bool bDeleteOverride = true;
                String sDelete_RowId = "";
                getDelOverrideAccess(ref bDeleteOverride, dsePageInfo.Tables["page"].Rows[0]["page_id"].ToString(), dsePageInfo.Tables["page"].Rows[0]["page_table_name"].ToString(), ref sDelete_RowId);
                Control cCell = null;
                if (create || edit) putEditButtons(ref DDI, ref cCell);
                if (create) putCpyButtons(ref DDI, ref cCell);
                if (delete) putDelButtons(ref DDI, ref cCell, bDeleteOverride, sDelete_RowId);

                // Added by srivatsan on Mar 25 2009 for PrintPage
                if (HDS.getObjectRightsForUser(dsePageInfo.Tables["Page"].Rows[0]["object_id"].ToString(), "read"))
                {
                    putPrintButtons(DDI);
                }

                if (create || edit || delete)
                {
                    if (cCell != null)
                    {
                        cCell.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;"));
                    }
                }
            }

            AddNotesSection(dsePageInfo); // Added by srivatsan on Sep 29 2009 for notes changes

            AddDocumentsSection(dsePageInfo); // Added by 'Imran Gani' on Sep 18 2012 for documents changes
            ShowSectionsAsTabs(dsePageInfo); // Added by 'Imran Gani' on 31-May-2013, to handle sections as tabs
            AddTaskSection(dsePageInfo); // Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts

            showadditionalsections(); // Added by srivatsan on Jan 29 2009 for NextStep sections 

            if (Request.QueryString["CPY"] == null)
            {
                if (Request.QueryString["PK"] != null)
                {
                    DataTable dtChilds = DDI.getAllChildObjects(strPagesetRowId);
                    if (dtChilds != null)//implemenetd by sanal on April 03, 2008
                        if (dtChilds.Rows.Count > 0)
                        {
                            HttpContext.Current.Session["PK"] = HttpContext.Current.Request.QueryString["PK"].ToString();
                            if(Request.QueryString["isDDE"]==null)// Added by srivatsan for DDE changes
                            Navigator.storeURL(Request.Url.ToString(), IsPostBack, false, false);
                            DDI.getPagesetandLoad(dtChilds, frmObj);
                        }
                }
            }

            if (!IsPostBack)
            {
                hdds.displayHelp(dsePageInfo.Tables["Page"], DDI.FindControl(frmObj.Controls, "imgHelp"));
                //if (imgHelp.OnClientClick == "") imgHelp.Visible = false;
            }
            if (Request.QueryString["VMODE"] != null)
            {
                if (Request.QueryString["VMODE"] == "1")
                {
                    setData();
                    loadAllVariables();
                    AddRelatedRecordsSections(dsePageInfo, strPagesetRowId);
                    UpdateActionButton(dsePageInfo);
                    return;
                }
            }
            else
                btnReset.Visible = true;
            CheckEditOperation();

            // Added by srivatsan for contol events
            if (!Page.IsPostBack)
            {
                PageControlEvents PCE = new PageControlEvents();
                PCE.DoControlEvents(frmObj, dsePageInfo);
            } //


        }
        loadAllVariables();

        // Added by srivatsan for Showing related records for transaction for edit/view mode
        AddRelatedRecordsSections(dsePageInfo, strPagesetRowId);

        //if (!Page.IsPostBack) // Added by srivatsan on Nov 03 2009 for action button
        //{
            UpdateActionButton(dsePageInfo);
        //}
            HideControlsForDEE();
            //AddEventForDDESave();
    }

    private void showmessage(string strErrorMsg)
    {
        try
        {
            lbl_message.Text = wrapItAsMessage(strErrorMsg, true);
            btnReset.Visible = false;
            btnSave.Visible = false;
            btnSaveNew.Visible = false;
            btnUpdate.Visible = false;
            td2.InnerHtml = "";
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("showmessage: Error: " + ex.Message);
        }
    }

    private void putEditButtons(ref DynamicDisplayI DDI,ref Control cCell)//implemented by sanal on 30th July 2008 , changed by Prithi on 4-Nov-2008
    {
        try
        {
            Control cc = cCell;
            if (cc == null)
                cc = DDI.FindControl(frmObj.Controls, "addButtons");//if multiple records page this will not be there
            if (cc == null) return;
            ImageButton b = new ImageButton();
            b = new ImageButton();
            b.ID = "btnEditTop";
            b.ImageUrl = "images/mb_button_edit.gif";
            b.ToolTip = "Edit";
            b.CausesValidation = false;
           // b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnEditTop','Loading...');");
            b.Click += new ImageClickEventHandler(btnEdit_Click);
            //b.UseSubmitBehavior = false;
            cc.Controls.Add(b);
            cc.Controls.Add(new LiteralControl("&nbsp;"));
            //if (Request.QueryString["CPY"] != null)
            //{
            //    if (Request.QueryString["CPY"] == "0")
            //    {
            //        b = new Button();
            //        b.ID = "btnSaveTop";
            //        b.Text = "Save";
            //        b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSave','Saving...');");
            //        b.Click += new EventHandler(btnSave_Click);
            //        b.UseSubmitBehavior = false;

            //        htc.Controls.Add(b);
            //        htc.Controls.Add(new LiteralControl("&nbsp;"));

            //        b = new Button();
            //        b.ID = "btnSaveNewTop";
            //        b.Text = "Save & Next";
            //        b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSaveNew','Saving...');");
            //        b.Click += new EventHandler(btnSaveNew_Click);
            //        b.UseSubmitBehavior = false;

            //        htc.Controls.Add(b);
            //        htc.Controls.Add(new LiteralControl("&nbsp;"));

            //        b = new Button();
            //        b.ID = "btnResetTop";
            //        b.Text = "Reset";
            //        //b.Click += new EventHandler(btnReset_Click);
            //        b.UseSubmitBehavior = false;
            //        b.OnClientClick = "aspnetForm.reset();return false;";
            //        b.UseSubmitBehavior = false;
            //        htc.Controls.Add(b);
            //    }
            //}
            //else if (Request.QueryString["PK"] == null)
            //{
            //    b = new Button();
            //    b.ID = "btnSaveTop";
            //    b.Text = "Save";
            //    b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSave','Saving...');");
            //    b.Click += new EventHandler(this.btnSave_Click);
            //    b.UseSubmitBehavior = false;

            //    htc.Controls.Add(b);
            //    htc.Controls.Add(new LiteralControl("&nbsp;"));

            //    b = new Button();
            //    b.ID = "btnSaveNewTop";
            //    b.Text = "Save & Next";
            //    b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSaveNew','Saving...');");
            //    b.Click += new EventHandler(btnSaveNew_Click);
            //    b.UseSubmitBehavior = false;

            //    htc.Controls.Add(b);
            //    htc.Controls.Add(new LiteralControl("&nbsp;"));

            //    b = new Button();
            //    b.ID = "btnResetTop";
            //    b.Text = "Reset";
            //    //b.Click += new EventHandler(btnReset_Click);
            //    b.UseSubmitBehavior = false;
            //    b.OnClientClick = "aspnetForm.reset();return false;";
            //    b.UseSubmitBehavior = false;
            //    htc.Controls.Add(b);
            //}
            //else
            //{
            //    b = new Button();
            //    b.ID = "btnUpdateTop";
            //    b.Text = "Save";
            //    b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnUpdate','Saving...');");
            //    b.Click += new EventHandler(btnUpdate_Click);
            //    b.UseSubmitBehavior = false;

            //    htc.Controls.Add(b);
            //    htc.Controls.Add(new LiteralControl("&nbsp;"));

            //    b = new Button();
            //    b.ID = "btnResetTop";
            //    b.Text = "Reset";
            //    //b.Click += new EventHandler(btnReset_Click);
            //    b.UseSubmitBehavior = false;
            //    b.OnClientClick = "aspnetForm.reset();return false;";
            //    b.UseSubmitBehavior = false;
            //    htc.Controls.Add(b);
            //}
            
            //htc.Attributes.Add("style", "padding-left:0px");
            cCell = cc;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in putHeaderButtons. Error: " + e.Message);
        }
    }
    private void putCpyButtons(ref DynamicDisplayI DDI, ref Control cCell) // implemented by Prithi on 4-Nov-2008
    {
        try
        {
            Control cc = cCell;
            if (cc == null)
                cc = DDI.FindControl(frmObj.Controls, "addButtons");//if multiple records page this will not be there
            if (cc == null) return;
            
            ImageButton b = new ImageButton();
            b = new ImageButton();
            b.ID = "btnCpyTop";
            b.ToolTip = "Copy";
            b.CausesValidation = false;
            b.ImageUrl = "images/mb_button_copy.gif";
            //b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnCpyTop','Loading...');");
            b.Click += new ImageClickEventHandler(btnCpy_Click);
            //b.UseSubmitBehavior = false;
            cc.Controls.Add(b);
            
            //htc.VAlign = "right";
            cc.Controls.Add(new LiteralControl("&nbsp;"));
            //htc.Attributes.Add("style", "padding-left:0px");
            cCell = cc;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in putHeaderButtons. Error: " + e.Message);
        }
    }
    private string includeJavascriptEscapes(string inp)
    {
        if (inp.Trim() == "") return inp;
        try
        {
            string[] orgChars = new string[] { "\\", "\'", "\"" };
            string[] replaces = new string[] { "\\\\", "\\'", "\\\"" };
            for (int i = 0; i < orgChars.Length; i++)
                inp = inp.Replace(orgChars[i], replaces[i]);
            return inp;
        }
        catch (Exception e)
        {
            return inp;
        }
    }
    private void putDelButtons(ref DynamicDisplayI DDI, ref Control cCell, bool AccessOverride, String Message) // Implemented by Prithi on 4-Nov-2008
    {
        try
        {
            Control cc = cCell;
            if (cc == null)
                cc = DDI.FindControl(frmObj.Controls, "addButtons");//if multiple records page this will not be there
            if (cc == null) return;
            
            ImageButton b = new ImageButton();
            b = new ImageButton();           
            b.ID = "btnDelTop";
            b.ToolTip = "Delete";
            b.CausesValidation = false;
            b.ImageUrl = "images/mb_button_delete.gif";
            //b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnDelTop','Deleting...');");           
            if (AccessOverride)
            {
                DataTable dtaPage = new DataTable();
                dtaPage = dsePageInfo.Tables["Page"];
                string strtable = dtaPage.Rows[0]["page_table_name"].ToString();
                string strsql = "select * from " + strtable + " where af_row_id = '" + Request.QueryString["PK"].ToString() + "'";
                HDDatabase hd = new HDDatabase();
                DataTable drr = new DataTable();
                drr = hd.GetDataTable(strsql);
                string strname = drr.Rows[0][2].ToString();
                if (hasChild(ref dsePageInfo))
                    b.OnClientClick = @"javascript:if(!confirm(""Are you sure you want to delete this Record ?\r Note: Child records will also be deleted."")){return false;};";
                else
                    b.OnClientClick = @"javascript:if(!confirm(""Are you sure you want to delete this Record ?"")){return false;};";
            }
            else
            {
                b.OnClientClick = @"javascript:alert(""" + includeJavascriptEscapes(Message) + @""");return false;";
            }
            b.Click += new ImageClickEventHandler(btnDel_Click);        
            cc.Controls.Add(b);
            cc.Controls.Add(new LiteralControl("&nbsp;"));
            cCell = cc;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in putHeaderButtons. Error: " + e.Message);
        }
    }
    private bool hasChild(ref DataSet PageInfo)
    {
        bool bReturn = false;

        try
        {
            string sObject_id = PageInfo.Tables["Page"].Rows[0]["object_id"].ToString();
            string sSQL = "select * from sy_obj_mas_detail where master_obj='" + sObject_id + "'";
            HDDatabase HDD = new HDDatabase();
            DataTable dt = HDD.GetDataTable(sSQL);
            if (dt != null)
                if (dt.Rows.Count > 0)
                    bReturn = true;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("hasChild : Error : " + ex.Message);
            bReturn = false;
        }

        return bReturn;
    }
    private void putHeaderButtons(DynamicDisplayI DDI)//implemented by sanal on 17th April 2008
    {
        try
        {
            Control cc = DDI.FindControl(frmObj.Controls, "addButtons");//if multiple records page this will not be there
            if (cc == null) return;
            HtmlTableCell htc = (HtmlTableCell)cc;
            Button b = new Button();
            if (Request.QueryString["CPY"] != null)
            {
                if (Request.QueryString["CPY"] == "0")
                {
                    b = new Button();
                    b.ID = "btnSaveTop";
                    b.Text = "Save";
                    b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSave','Saving...'); return false;");
                    b.Click += new EventHandler(btnSave_Click);                    
                    b.UseSubmitBehavior = false;

                    htc.Controls.Add(b);
                    htc.Controls.Add(new LiteralControl("&nbsp;"));

                    b = new Button();
                    b.ID = "btnSaveNewTop";
                    b.Text = "Save & Next";
                    b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSaveNew','Saving...');");
                    b.Click += new EventHandler(btnSaveNew_Click);
                    b.UseSubmitBehavior = false;

                    htc.Controls.Add(b);
                    htc.Controls.Add(new LiteralControl("&nbsp;"));

                    b = new Button();
                    b.ID = "btnResetTop";
                    b.Text = "Reset";
                    //b.Click += new EventHandler(btnReset_Click);
                    b.UseSubmitBehavior=false;
                    b.OnClientClick = "aspnetForm.reset();return false;";
                    b.UseSubmitBehavior = false;
                    htc.Controls.Add(b);
                }
            }
            else if (Request.QueryString["PK"] == null)
            {
                b = new Button();
                b.ID = "btnSaveTop";
                b.Text = "Save";
                b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSave','Saving...'); return false;");
                b.Click += new EventHandler(this.btnSave_Click);
                b.UseSubmitBehavior = false;

                htc.Controls.Add(b);
                htc.Controls.Add(new LiteralControl("&nbsp;"));

                b = new Button();
                b.ID = "btnSaveNewTop";
                b.Text = "Save & Next";
                b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnSaveNew','Saving...');");
                b.Click += new EventHandler(btnSaveNew_Click);
                b.UseSubmitBehavior = false;

                htc.Controls.Add(b);
                htc.Controls.Add(new LiteralControl("&nbsp;"));

                b = new Button();
                b.ID = "btnResetTop";
                b.Text = "Reset";
                //b.Click += new EventHandler(btnReset_Click);
                b.UseSubmitBehavior = false;
                b.OnClientClick = "aspnetForm.reset();return false;";
                b.UseSubmitBehavior = false;
                htc.Controls.Add(b);
            }
            else
            {

                //htc.Controls.Add(new LiteralControl("&nbsp;"));

                b = new Button();
                b.ID = "btnUpdateTop";
                b.Text = "Save";
                b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnUpdate','Saving...'); return false;");
                b.Click += new EventHandler(btnUpdate_Click);
                b.UseSubmitBehavior = false;

                htc.Controls.Add(b);
                htc.Controls.Add(new LiteralControl("&nbsp;"));

                b = new Button();
                b.ID = "btnResetTop";
                b.Text = "Reset";
                //b.Click += new EventHandler(btnReset_Click);
                b.UseSubmitBehavior = false;
                b.OnClientClick = "aspnetForm.reset();return false;";
                b.UseSubmitBehavior = false;
                htc.Controls.Add(b);
            }
            htc.Align = "Center";
            htc.Attributes.Add("style", "padding-left:0px");
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in putHeaderButtons. Error: " + e.Message);
        }
    }

    private void destroyUnwantedObjects()//implemented by sanal on 27 Feb 2008
    {
        try
        {
            Session["dtWorkflow"] = null;
        }
        catch (Exception e)
        {

        }
    }

    private void setRequestURL()//implemented by sanal on 13 Dec 2007
    {
        hfRequestURL.Value = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();// +pk;        
        
        /*if (!IsPostBack)
        {
            hfRequestURL.Value = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();// +pk;
            if (Request.RawUrl.ToLower().Contains("dynamicscreen.aspx") && Request.UrlReferrer.OriginalString.ToLower().Contains("dynamicscreen.aspx"))
                hfRequestURL.Value = Request.UrlReferrer.OriginalString;
        }*/

    }

    public string ReplaceVariables(string value)
    {
        HDDatabase HDD = new HDDatabase();

        try
        {
            if (sysVar != null)
            {
                foreach (string sKey in sysVar.Keys)
                {
                    string temp = "";
                    
                    if (sKey.StartsWith("{") && sKey.EndsWith("}"))
                    {
                        temp = sKey;
                    }
                    else
                    {
                        string sObject_table = sKey.Substring(0, sKey.IndexOf("."));
                        //string sSql = "Select object_id from sy_obj where object_table='" + sObject_table + "'";
                        //string sObject_id = HDD.GetColumnValue(sSql);
                        string sObject_id = CommonFunctions.GetColValueFromPageInfo(strPagesetRowId, "sy_obj", "object_id", "object_table='" + sObject_table + "'");
                        temp = "[" + sKey.Replace(sObject_table, sObject_id) + "]";
                    }
                    
                    if (value.Contains(temp))
                        value = value.Replace(temp, sysVar[sKey].ToString());
                }
            }
            Hashtable hsAppVar = new Hashtable();
            hdds.loadAppVariables(ref hsAppVar);

            if (hsAppVar != null)
            {
                foreach (string sKey in hsAppVar.Keys)
                {
                    if (value.Contains(sKey))
                        value = value.Replace(sKey, hsAppVar[sKey].ToString());
                }
            }
            //if (GlobalValues.hsAppVar != null)
            //{
            //    foreach (string sKey in GlobalValues.hsAppVar.Keys)
            //    {
            //        if (value.Contains(sKey))
            //            value = value.Replace(sKey, GlobalValues.hsAppVar[sKey].ToString());
            //    }
            //}

            return value;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in ReplaceVariables function: " + e.Message);
            return "";
        }
    }
    
    private void loadSystemVariables()
    {
        try
        {
            DataSet ds = new DataSet();
            string dsTemp = "";
            HDDatabase db = new HDDatabase();
            ds = db.GetDataset("select * from sy_var");
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    switch (dr["sy_var_type"].ToString())
                    {
                        case "DQ"://database query
                            dsTemp = db.GetColumnValue(ReplaceVariables(dr["sy_var_value"].ToString()));  
                            //sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dsTemp);
                            if (dsTemp != "") // Modified by 'Imran Gani' on 21-Dec-2012, to get the default value.
                                sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dsTemp);
                            else
                                sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dr["sy_var_defaultvalue"]);
                            break;
                        case "CO"://constant
                            if (dr["sy_var_value"].ToString().Length>0)
                                sysVar.Add("{!" + dr["sy_var_name"].ToString() + "}", dr["sy_var_value"]);
                            else
                                sysVar.Add("{!" + dr["sy_var_name"].ToString()+ "}", dr["sy_var_defaultvalue"]);
                            break;
                    }                                        
                }
            }
            ds = null;
            db = null;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in loadSystemVariables function: " + e.Message);
        }
    }
    
    private void setData()
    {
        string sPageKey = "";
        if (Request.QueryString["PK"] != null)
            sPageKey = Request.QueryString["PK"].ToString();
        Master MA = new Master();
        bool blnStatus = MA.EditOperation(dsePageInfo, frmObj, sPageKey);
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
            Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
        }
        lblKey.Visible = false;
        lblKeyAttr.Visible = false;
        btnSave.Visible = false;
        btnSaveNew.Visible = false;
        //btnSaveTop.Visible = btnSave.Visible;
        btnUpdate.Visible = false;
        //btnUpdateTop.Visible = btnUpdate.Visible;
        btnReset.Visible = false;
        //btnResetTop.Visible = btnReset.Visible;
    }

    private bool CheckEditOperation()
    {
        bool blnStatus = true;
        string strPageKey = "";
        bool IsEdit = false;
        //if (Page.IsPostBack == false)
        //{
            if (Request.QueryString["PK"] != null)
            {
                strPageKey = Request.QueryString["PK"].ToString();
                IsEdit = true;
            }
            if (IsEdit)
            {
                Master MA = new Master();
                blnStatus = MA.EditOperation(dsePageInfo, frmObj, strPageKey);
                if (blnStatus == false)
                {
                    strErrMessage = MA.ErrorMessage;
                    Response.Write("<font color='red'>Error : " + strErrMessage + "</font>");
                }
            }
        //}

        if (Request.QueryString["CPY"] != null)
        {
            if (Request.QueryString["CPY"] == "0")
            {
                btnSave.Visible = true;
                btnSaveNew.Visible = true;
                //btnSaveTop.Visible = true;
                btnUpdate.Visible = false;
                //btnUpdateTop.Visible = false;
                //TextBox txtID = (TextBox)frmObj.FindControl("ContentPlaceHolder").FindControl("");
            }
        }
        else if (Request.QueryString["PK"] == null)
        {
            btnSave.Visible = true;
            btnSaveNew.Visible = true;
            //btnSaveTop.Visible = true;
            btnUpdate.Visible = false;
            //btnUpdateTop.Visible = false;
        }
        else
        {
            btnUpdate.Visible = true;
            //btnUpdateTop.Visible = true;
            btnSave.Visible = false;
            btnSaveNew.Visible = false;
            //btnSaveTop.Visible = false;
        }
        return blnStatus;
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    private bool SaveData()
    {
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowId, frmObj, dsePageInfo,true);
        if (SR.errormessage != "")
        {
            //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
            strErrMessage = SR.errormessage;
            lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + HttpUtility.HtmlEncode(strErrMessage), true) ;
            return false;
        }


        //setDefaultValues(dseInputInfo,true);

        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "INSERT");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }
    #region default_value_settings - can be removed if the version 06 goes ok with the primary key changes
    
    ////////private string getRandomString(int size, bool toUpperCase, ref Random random)
    ////////{
    ////////    System.Text.StringBuilder builder = new System.Text.StringBuilder();
    ////////    char ch;
    ////////    for (int i = 0; i < size; i++)
    ////////    {
    ////////        ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
    ////////        builder.Append(ch);
    ////////    }
    ////////    if (toUpperCase)
    ////////        return builder.ToString().ToUpper();
    ////////    return builder.ToString();
    ////////}
    ////////private string GenerateId()
    ////////{
    ////////    long i = 1;
    ////////    foreach (byte b in Guid.NewGuid().ToByteArray())
    ////////    {
    ////////        i *= ((int)b + 1);
    ////////    }
    ////////    return string.Format("{0:x}", i - DateTime.Now.Ticks);//converts to hexa decimal
    ////////}
    ////////private string getHashKey()
    ////////{
    ////////    string temp = GenerateId();
    ////////    if (temp.Length != 16)
    ////////    {
    ////////        Random rnd = new Random();
    ////////        temp += getRandomString(16 - temp.Length, true, ref rnd);
    ////////        rnd = null;
    ////////    }
    ////////    return temp;
    ////////}
    ////////private void setDefaultValues(DataSet inputInfo,bool saveMode)//created by sanal on 13 Dec 2007
    ////////{
    ////////    //string ss = HttpContext.Current.Session["userid"].ToString().Replace("'", "''");
    ////////    string hashKey = "";
    ////////    try
    ////////    {
    ////////        foreach (DataTable dt in inputInfo.Tables)
    ////////        {
    ////////            foreach (DataColumn dc in dt.Columns)
    ////////            {
    ////////                foreach (DataRow dr in dt.Rows)
    ////////                {
    ////////                    switch (dc.ColumnName.ToLower())
    ////////                    {
    ////////                        case "af_row_id":
    ////////                            if (dr[dc.ColumnName].ToString() == "" || saveMode)
    ////////                            {
    ////////                                if (hashKey == "") hashKey = getHashKey();
    ////////                                dr[dc.ColumnName] =  hashKey;
    ////////                            }
    ////////                            break;
    ////////                        case "created_by":
    ////////                            if (dr[dc.ColumnName].ToString() == "" || saveMode)
    ////////                            {
    ////////                                //if (sysVar.ContainsKey("Current User"))
    ////////                                //    dr[dc.ColumnName] = sysVar["Current User"].ToString();
    ////////                                dr[dc.ColumnName] = Session["userid"].ToString();
    ////////                            }
    ////////                            break;
    ////////                        case "modified_at":
    ////////                            dr[dc.ColumnName] = System.DateTime.Now.ToUniversalTime().ToString();
    ////////                            break;
    ////////                        case "created_at":
    ////////                            if (dr[dc.ColumnName].ToString() == "" || saveMode)
    ////////                                dr[dc.ColumnName] = System.DateTime.Now.ToUniversalTime().ToString();
    ////////                            break;
    ////////                        case "modified_by":
    ////////                            dr[dc.ColumnName] = Session["userid"].ToString();
    ////////                            break;
    ////////                    }
    ////////                }
    ////////            }
    ////////        }
    ////////    }
    ////////    catch (Exception e)
    ////////    {
    ////////        LogWriter.WriteLog("Error in setDefaultValues. Error: " + e.Message);
    ////////    }
    ////////}
    #endregion
    private void loadAllVariables()//created by sanal on Oct 18, 2007 for sys var implementation
    {
        Hashtable hsAppVar = new Hashtable();
        hdds.loadAppVariables(ref hsAppVar);

        sysVar = new Hashtable();
        if (dsePageInfo.Tables.Count > 0)
            loadPageVariables(dsePageInfo);
        loadSystemVariables();        
        
        //GlobalValues.hsSysVar = sysVar;
        Session["SysVar"] = sysVar;
    }
    //private void loadAppVariables()
    //{
    //    security hds = new security();
    //    if (HttpContext.Current.Session["company_id"] != null) hds.Insert_AppVariable("current_company", HttpContext.Current.Session["company_id"].ToString());
    //    if (HttpContext.Current.Session["user_afrowid"] != null) hds.Insert_AppVariable("current_userafrowid", HttpContext.Current.Session["user_afrowid"].ToString());
    //    if (HttpContext.Current.Session["userid"] != null) hds.Insert_AppVariable("current_userid", HttpContext.Current.Session["userid"].ToString());
    //    if (HttpContext.Current.Session["user_name"] != null) hds.Insert_AppVariable("current_username", HttpContext.Current.Session["user_name"].ToString());
    //    hds = null;
    //}
    private void loadPageVariables(DataSet dsInp)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        try
        {
            string tableName = ""; string pageId = "";            
            DataTable dt = dsInp.Tables["Page"];            
            foreach (DataRow dr in dt.Rows)
            {
                tableName = dr["page_table_name"].ToString();
                pageId = dr["page_id"].ToString();
                DataRow[] drs = dsInp.Tables["PageCtrl"].Select("page_id='" + dr["af_row_id"].ToString() + "'");//DataRow[] drs = dsInp.Tables["PageCtrl"].Select("page_id='" + dr["page_id"].ToString() + "'");
                for (int i = 0; i < drs.Length; i++)                
                    getControlValue(tableName, drs[i]["control_id"].ToString(), pageId);                
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in loadPageVariables function: " + e.Message);
        }
    }
    private void getControlValue(string tableName, string controlName, string pageId)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        Control cInp;
        DynamicDisplayI di = new DynamicDisplayI();
        cInp  = di.FindControl(this.Controls, pageId + "_" + controlName);
        di = null;
        tableName = tableName + "." + controlName;
        if (cInp != null)
        {
            switch (cInp.GetType().ToString())
            {
                case "System.Web.UI.WebControls.TextBox":
                    TextBox tb = (TextBox)cInp;
                    sysVar.Add(tableName, tb.Text);
                    break;
                case "System.Web.UI.WebControls.DropDownList":
                    DropDownList db = (DropDownList)cInp;
                    sysVar.Add(tableName, db.SelectedValue);
                    break;
                case "System.Web.UI.WebControls.CheckBox":
                    CheckBox cb = (CheckBox)cInp;
                    sysVar.Add(tableName, cb.Checked);
                    break;
                case "System.Web.UI.WebControls.CheckBoxList":
                    CheckBoxList cbl = (CheckBoxList)cInp;
                    //sysVar.Add(tableName, tb.se);
                    break;
                case "System.Web.UI.WebControls.RadioButton":
                    RadioButton rb = (RadioButton)cInp;
                    sysVar.Add(tableName, rb.Checked);
                    break;
                case "System.Web.UI.WebControls.RadioButtonList":
                    RadioButtonList rbl = (RadioButtonList)cInp;
                    //hInp.Add(tableName, tb.Text);
                    break;
                case "System.Web.UI.WebControls.HiddenField":
                    HiddenField hf = (HiddenField)cInp;
                    sysVar.Add(tableName, hf.Value);
                    break;
            }
        }
    }
    private void loadPageVariables(ControlCollection mainControl)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        foreach (Control cc in mainControl)
        {
            if (cc.Controls.Count < 1)
            {
                if (cc.ID != null)
                    if (cc.Controls.Count < 1)
                        add2HashTable(cc, sysVar);
            }
            else
                loadPageVariables(cc.Controls);
        }
    }
    private void add2HashTable(Control cInp,Hashtable hInp)//created by sanal on Oct 18, 2007 for sys var implementation
    {
        switch (cInp.GetType().ToString())
        {
            case "System.Web.UI.WebControls.TextBox":
                TextBox tb = (TextBox)cInp;
                hInp.Add(cInp.ID,tb.Text);
                break;
            case "System.Web.UI.WebControls.DropDownList":
                DropDownList db = (DropDownList)cInp;
                hInp.Add(cInp.ID, db.SelectedValue);
                break;
            case "System.Web.UI.WebControls.CheckBox":
                CheckBox cb = (CheckBox)cInp;
                hInp.Add(cInp.ID, cb.Checked);
                break;
            case "System.Web.UI.WebControls.CheckBoxList":
                CheckBoxList cbl = (CheckBoxList)cInp;
                //hInp.Add(cInp.ID, tb.se);
                break;
            case "System.Web.UI.WebControls.RadioButton":
                RadioButton rb = (RadioButton)cInp;
                hInp.Add(cInp.ID, rb.Checked);
                break;
            case "System.Web.UI.WebControls.RadioButtonList":
                RadioButtonList rbl = (RadioButtonList)cInp;
                //hInp.Add(cInp.ID, tb.Text);
                break;
                case "System.Web.UI.WebControls.HiddenField":
                HiddenField hf = (HiddenField)cInp;
                hInp.Add(cInp.ID, hf.Value);
                break;
        }
    }
    private object getVariableName(string variableName)
    {
        if (sysVar!=null)
            if (sysVar.ContainsKey(variableName))
                return sysVar[variableName];
        return null;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        loadAllVariables();
        if (SaveData())
        {
            /*if (HttpContext.Current.Session["PK"] != null)
                if (HttpContext.Current.Session["PK"].ToString() != "")
                    HttpContext.Current.Session.Remove("PK");*/
            //Added by srivatsan
            if (Request.QueryString["isDDE"] != null)
            {
                SetValueForDDE();
                //Response.Write("<script language=\"javascript\">javascript:SetValueForDDE('" + Request.QueryString["isDDE"].ToString() + "','" + storagefield + "','" + displayfield + "','" + pagemode + "');</script>");
                //Response.Write("<script>self.close();</script>");

            }
            else
            {
                string ret = getURL();//implemented by sanal on 13 Dec 2007
                if (ret != "")
                    Response.Redirect(ret, true);
                else
                    lbl_message.Text = wrapItAsMessage("Data Inserted Successfully",false);
            }
        }
        else
        {
            Master objMaster = new Master();
            if (objMaster.DeleteMessage != "")
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + HttpUtility.HtmlEncode(objMaster.DeleteMessage),true);
                objMaster.DeleteMessage = "";
            }
            else
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + HttpUtility.HtmlEncode(ErrorMessage), true);
            }
        }
    }
    private string getURL()//implemented by sanal on 13 Dec 2007
    {
        try
        {
            //return hfRequestURL.Value;
            if (HttpContext.Current.Session["URLs"] == null)
                return hfRequestURL.Value;
            else
            {
                return Navigator.getURL(Request.Url.ToString());
            }
            //return Session["naviURL"].ToString();
            //return "DisplayGrid.aspx?mn=" + Request.QueryString["mn"].ToString() + "&pgs_id=" + Request.QueryString["pgs_id"].ToString();
        }
        catch (Exception e)
        {
            return "";
        }        
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        loadAllVariables();
        if (UpdateData())
        {
            if (Request.QueryString["isDDE"] != null)
            {
                SetValueForDDE();
                    //Response.Write("<script>self.close();</script>");   
            }
            else
            {
                string ret = getURL();//implemented by sanal on 13 Dec 2007
                if (ret != "")
                    Response.Redirect(ret, true);
                else
                    lbl_message.Text = wrapItAsMessage("Data Updated Successfully", false);
            }
        }
        else
        {
            Master objMaster = new Master();
            if (objMaster.DeleteMessage != "")
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. " + HttpUtility.HtmlEncode(objMaster.DeleteMessage),true);
                objMaster.DeleteMessage = "";
            }
            else
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. " + HttpUtility.HtmlEncode(ErrorMessage),true);
            }
        }
    }

    private bool UpdateData()
    {
        bool blnStatus = true;
        ScreenReader SR = new ScreenReader();
        dseInputInfo = SR.CaptureData(strPagesetRowId, frmObj, dsePageInfo,false);
        if (SR.errormessage != "")
        {
            //Code added by Sampath on 18-Nov-2011 for IPP Vertical privilege
            strErrMessage = SR.errormessage;
            lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Update not successful. " + HttpUtility.HtmlEncode(strErrMessage),true);
            return false;
        }
        //setDefaultValues(dseInputInfo,false);

        Master MA = new Master();
        blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, "UPDATE");
        if (blnStatus == false)
        {
            strErrMessage = MA.ErrorMessage;
        }
        return blnStatus;
    }

    public string ErrorMessage
    {
        get
        {
            return this.strErrMessage;
        }
    }
    
    protected void btnReset_Click(object sender, EventArgs e)
    {
        if (IsPostBack)
            Server.Transfer(Request.RawUrl,true);
    }
    protected void btnEdit_Click(object sender, EventArgs e) // Implemented by Prithi on 4-Nov-2008 
    {
        try
        {
            bool bEditOverride = true;
            String sEdit_RowId = "";
            getEditOverrideAccess(ref bEditOverride, dsePageInfo.Tables["page"].Rows[0]["page_id"].ToString(), dsePageInfo.Tables["page"].Rows[0]["page_table_name"].ToString(), ref sEdit_RowId);

            if (bEditOverride)
            {
                ArrayList alURLs = new ArrayList();
                alURLs = (ArrayList)HttpContext.Current.Session["URLs"];
                if (alURLs[alURLs.Count - 1].ToString().Contains("&VMODE=1"))
                {
                    if (Request.QueryString["PK"] == HttpContext.Current.Session["PK"])
                    {
                        alURLs.RemoveAt(alURLs.Count - 1);
                    }
                }
                string url = Request.Url.ToString().ToLower();
                url = url.ToString().Replace("&vmode=1", "").Replace("&vmode=0", "");
                if (url != "")
                {
                    if (Request.QueryString["PK"] != null)
                    {
                        if (HttpContext.Current.Session["PK"] != null)
                        {
                            if (ischild(strPagesetRowId))
                            {
                                url = url + "&MK=" + HttpContext.Current.Session["PK"].ToString() + @"";
                            }
                        }
                        else
                        {
                            url = url;
                        }

                        Response.Redirect(url, true);
                    }
                }
            }
            else
            {
                String url = @"" + "NoAccess.aspx" + @"?pgs_id=" + strPagesetRowId + "&PK=" + sEdit_RowId
                                    + "&mn=" + Request.QueryString["mn"] + @"";
                Response.Redirect(url, true);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in btnEdit_Click function: " + ex.Message);
        }

    }
    protected void btnCpy_Click(object sender, EventArgs e)  // Implemented by Prithi on 4-Nov-2008 
    {
        try
        {
            ArrayList alURLs = new ArrayList();
            alURLs = (ArrayList)HttpContext.Current.Session["URLs"];
            if (alURLs[alURLs.Count - 1].ToString().Contains("&VMODE=1"))
            {
                if (Request.QueryString["PK"] == HttpContext.Current.Session["PK"])
                {
                    alURLs.RemoveAt(alURLs.Count - 1);                   
                }
            }
            string url = Request.Url.ToString();
            url = url.ToString().Replace("&vmode=1", "").Replace("&vmode=0", "").Replace("&VMODE=1", "").Replace("&VMODE=0", "");
            System.Text.StringBuilder txt = new System.Text.StringBuilder(url);
            txt.Append("&CPY=0");
            url = txt.ToString();
            if (url != "")
            {
                if (Request.QueryString["PK"] != null)
                {
                    if (HttpContext.Current.Session["PK"] != null)
                    {
                        if (ischild(strPagesetRowId))
                        {
                            url = url + "&MK=" + HttpContext.Current.Session["PK"].ToString() + @"";
                        }
                    }
                    else
                    {
                        url = url;
                    }

                    Response.Redirect(url, true);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in btnCpy_Click function: " + ex.Message);
        }
    }
    private bool ischild(string strPagesetRowId)
    {
        bool schild = false;
        try
        {
            string sPage_id = "";
            string sObject_Id = "";
            string sAF_ROW_ID = "";
            string obj_id = "";
            string ischild = "";
            HDDatabase HDD = new HDDatabase();
            string sSql = "select af_row_id from sy_pgs where pageset_id='" + strPagesetRowId + "'";
            //string sSql = "select pg.object_id from sy_pg pg inner join sy_pgs_mem pgs_mem on pg.page_id=pgs_mem.page_id inner join sy_pgs pgs on pgs.af_row_id=pgs_mem.pageset_id where pgs.pageset_id = '" + strPagesetRowId + "'";
            //sAF_ROW_ID = HDD.GetColumnValue(sSql);
            sSql = "select page_id from sy_pgs_mem where pageset_id='" + strPagesetRowId + "'";
            sPage_id = HDD.GetColumnValue(sSql);
            sSql = "select object_id from sy_pg where page_id='" + sPage_id + "'";
            sObject_Id = HDD.GetColumnValue(sSql);
            sSql = "select is_child from sy_obj where object_id='" + sObject_Id + "'";
            ischild = HDD.GetColumnValue(sSql);
            sSql = "select object_id from sy_obj_mas_detail where object_id='" + ischild + "'";
            obj_id = HDD.GetColumnValue(sSql);
            if (obj_id != "")
            {
                if (obj_id == ischild)
                {
                    schild = true;
                    return schild;
                }
            }
            return schild;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("IsChild : Error : " + ex.Message);
        }
        return schild;
    }
    protected void btnDel_Click(object sender, EventArgs e)  // Implemented by Prithi on 4-Nov-2008 
    {
        try
        {
            string strDelKey = "";
            string strPagesetRowId = "";
            if (Request.QueryString["pgs_id"] != null)
            {
                strPagesetRowId = Request.QueryString["pgs_id"].ToString();
            }

            if (Request.QueryString["PK"] != null)
            {
                strDelKey = Request.QueryString["PK"].ToString().Replace("'", "''");
            }
            if (strDelKey != "")
            {
                string ret = getURL();
                if (ret != "")
                {
                    if (ret.Contains("DynamicScreen"))
                    {
                        DataSet dsePageInfo = new DataSet();
                        PageInfoLoad PIL = new PageInfoLoad();
                        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);

                        Master MA = new Master();
                        bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
                        if (blnStatus)
                        {
                            string ret1 = getURL();
                            if (ret1 != "")
                            {
                                Response.Redirect(ret1, true);

                            }

                        }
                    }
                    else if (ret.Contains("DisplayGrid") || ret.Contains("Search"))
                    {
                        //ret = ret + "&DPK=" + strDelKey + @"";
                        //Response.Redirect(ret, true);

                        DataSet dsePageInfo = new DataSet();
                        PageInfoLoad PIL = new PageInfoLoad();
                        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);

                        Master MA = new Master();
                        Session["DPK"] = strDelKey;
                        bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
                        Session["DPK"] = null;

                        Response.Redirect(ret, true);

                    }
                    else Response.Redirect(ret, true);
                }

            }

        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in btnDel_Click. Error: " + ex.Message);
        }

    }
    protected void btnSaveNew_Click(object sender, EventArgs e)
    {
        loadAllVariables();
        if (SaveData())
        {
            /*if (HttpContext.Current.Session["PK"] != null)
                if (HttpContext.Current.Session["PK"].ToString() != "")
                    HttpContext.Current.Session.Remove("PK");*/
            string ret = HttpContext.Current.Request.Url.AbsolutePath + "?pgs_id=" + HttpContext.Current.Request.QueryString["pgs_id"] + "&mn=" + HttpContext.Current.Request.QueryString["mn"];

            if(Request.QueryString["isDDE"]!=null)
                ret = ret + "&isDDE=" + Request.QueryString["isDDE"];

            if (Request.QueryString["MK"] != null && ret != "")
                ret = ret + "&MK=" + Request.QueryString["MK"];

            if (ret != "")
                Response.Redirect(ret, true);
            else
                lbl_message.Text = wrapItAsMessage("Data Inserted Successfully", false);
        }
        else
        {
            Master objMaster = new Master();
            if (objMaster.DeleteMessage != "")
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + HttpUtility.HtmlEncode(objMaster.DeleteMessage),true);
                objMaster.DeleteMessage = "";
            }
            else
            {
                lbl_message.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data Insert not successful. " + HttpUtility.HtmlEncode(ErrorMessage), true);
            }
        }
    }

    private void showadditionalsections() // Added by srivatsan for next step and related info
    {
        AdditionalPageInfo addinfo = new AdditionalPageInfo(strPagesetRowId, dsePageInfo);
        try
        {
            HtmlTableCell htc1 = new HtmlTableCell();
            HtmlTableRow htr1 = new HtmlTableRow();
            htc1.ID = "tdpagesteps1";
            htc1.Width = "100%";
            bool canshowpagesteps = true; // addinfo.loadpagesteps(strPagesetRowId, ref htc1, false); // Commanded by 'Imran Gani' on 30-Aug-12, to avoid next step at the bottom of the page.
            htr1.Controls.Add(htc1);
            htc1 = new HtmlTableCell();
            htc1.Controls.Add(htr1);

            if (canshowpagesteps == true)
            {
                tdadditionalsections.Controls.Add(htc1);

                HtmlTableRow htr3 = new HtmlTableRow();
                HtmlTableCell htc3 = new HtmlTableCell();
                htc3.Height = "10px";
                htc3.Width = "100%";
                tdadditionalsections.Controls.Add(htc3);




                // Added by srivatsan for Next step in page Header



                Label lbjobj = (Label)frmObj.FindControl("lbl_appmaster_nextstep");
                lbjobj.Visible = true;

                HtmlTable htnextstep = new HtmlTable();
                //htnextstep.Width = "100%"; // Commanded by 'Imran Gani' on 24-Oct-13, to control the width in all browsers - especially chrome.
                htnextstep.CellPadding = 0;
                htnextstep.CellSpacing = 0;
                htnextstep.Border = 0;
                HtmlTableRow htrnextstep = new HtmlTableRow();
                HtmlTableCell htcnextstep = new HtmlTableCell();
                htcnextstep.ID = "td_dynamicpage_nextstep";
                htcnextstep.Width = "100%";
                htcnextstep.NoWrap = true;
                //htcnextstep = htc1;
                addinfo.loadpagesteps(strPagesetRowId, ref htcnextstep,true);

                htrnextstep.Controls.Add(htcnextstep);
                htnextstep.Controls.Add(htrnextstep);



                HtmlGenericControl gencon = (HtmlGenericControl)frmObj.FindControl("div_nextstep");

                gencon.Controls.Add(htnextstep);




                //
            }
            else
            {
                if (frmObj.FindControl("lbl_appmaster_nextstep") != null)
                {
                    Label lbjobj = (Label)frmObj.FindControl("lbl_appmaster_nextstep");
                    lbjobj.Visible = false;
                }
            }



            HtmlTableCell htc2 = new HtmlTableCell();
            HtmlTableRow htr2 = new HtmlTableRow();
            htc2.ID = "tdrelatedinfo1";
            htc2.Width = "100%";
            bool canshowrelatedinfo = true;// addinfo.loadrelatedinfo(ref htc2, 2, false); // Commanded by 'Imran Gani' on 15-Aug-12, to avoid Related Info at the bottom of the page.
            htr2.Controls.Add(htc2);
            htc2 = new HtmlTableCell();
            htc2.Controls.Add(htr2);
            if (canshowrelatedinfo == true)
            {
                tdadditionalsections.Controls.Add(htc2);


                Label lbjobj = (Label)frmObj.FindControl("lbl_appmaster_relatedinfo");
                lbjobj.Visible = true;


                HtmlTable htnextstep = new HtmlTable();
                //htnextstep.Width = "100%"; // Commanded by 'Imran Gani' on 24-Oct-13, to control the width in all browsers - especially chrome.
                htnextstep.CellPadding = 0;
                htnextstep.CellSpacing = 0;
                htnextstep.Border = 0;
                HtmlTableRow htrnextstep = new HtmlTableRow();
                HtmlTableCell htcnextstep = new HtmlTableCell();
                htcnextstep.ID = "td_dynamicpage_relatedinfo";
                htcnextstep.Width = "100%";
                htcnextstep.NoWrap = true;
                //htcnextstep = htc2;
                addinfo.loadrelatedinfo(ref htcnextstep, 2,true);
                htrnextstep.Controls.Add(htcnextstep);
                htnextstep.Controls.Add(htrnextstep);

                HtmlGenericControl gencon = (HtmlGenericControl)frmObj.FindControl("div_related");

                gencon.Controls.Add(htnextstep);
            }
            else
            {
                if (frmObj.FindControl("lbl_appmaster_relatedinfo") != null)
                {
                    Label lbjobj = (Label)frmObj.FindControl("lbl_appmaster_relatedinfo");
                    lbjobj.Visible = false;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error showadditionalsections: " + ex.Message);
        }
        finally
        {
            addinfo = null;
        }

        //
    }

    private void putPrintButtons(DynamicDisplayI DDI) // Added by srivatsan for PrintPage buttons
    {
        try
        {
            Control cc = DDI.FindControl(frmObj.Controls, "addButtons");//if multiple records page this will not be there
            if (cc == null) return;

            ImageButton b = new ImageButton();
            b = new ImageButton();
            b.ID = "btnprintTop";
            b.ToolTip = "Printer friendly page";
            b.CausesValidation = false;
            b.ImageUrl = "images/mb_button_print.GIF";
            //b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnCpyTop','Loading...');");
            //b.Click += new ImageClickEventHandler(btnCpy_Click);
            b.OnClientClick = "javascript:Popup=(window.open('Print.aspx?pgs_id=" + strPagesetRowId + "&PK=" + Request.QueryString["PK"].ToString() + "&mn=" + Request.QueryString["mn"].ToString() + "','Popup','toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=800,height=630,left=100,top=30')||window).focus(); return false;";
            //b.UseSubmitBehavior = false;
            cc.Controls.Add(b);

            //htc.VAlign = "right";
            cc.Controls.Add(new LiteralControl("&nbsp;"));
            //htc.Attributes.Add("style", "padding-left:0px");
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in putHeaderButtons. Error: " + e.Message);
        }
    }

    private void getOverrideAccess(ref bool bEdit, ref bool bDelete, String Page_id, string Object_Table_Name, ref String Edit_rowid, ref String Delete_rowid)
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            DataSet dsTemp = HDD.GetDataset("select * from sy_object_access_override where object='" + Page_id + "' and active='1';");

            foreach (DataRow dr in dsTemp.Tables[0].Rows)
            {
                switch (dr["action"].ToString().ToLower())
                {
                    case "edit":
                        bool bRecord = getOverrideForThisRecord(dr["condition"].ToString());
                        if (bRecord)
                        {
                            if (dr["mode"].ToString().ToLower() == "enable")
                            {
                                bEdit = true;
                            }
                            else if (dr["mode"].ToString().ToLower() == "disable")
                            {
                                bEdit = false;
                            }
                            Edit_rowid = dr["af_row_id"].ToString();
                        }
                        break;
                    case "delete":
                        bool bRecord1 =  getOverrideForThisRecord(dr["condition"].ToString());
                        if (bRecord1)
                        {
                            if (dr["mode"].ToString().ToLower() == "enable")
                            {
                                bDelete = true;
                            }
                            else if (dr["mode"].ToString().ToLower() == "disable")
                            {
                                bDelete = false;
                            }
                            Delete_rowid = dr["message"].ToString();
                        }
                        break;
                    default:
                        break;
                }
            }
            dsTemp.Dispose();
            dsTemp = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getOverrideAccess : Error : " + ex.Message);
        }
    }

    private void getDelOverrideAccess(ref bool bDelete, String Page_id, string Object_Table_Name, ref String Delete_rowid)
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            DataSet dsTemp = HDD.GetDataset("select * from sy_object_access_override where object='" + Page_id + "' and action='delete' and active='1';");

            foreach (DataRow dr in dsTemp.Tables[0].Rows)
            {
                switch (dr["action"].ToString().ToLower())
                {
                    case "delete":
                        bool bRecord1 = getOverrideForThisRecord(dr["condition"].ToString());
                        if (bRecord1)
                        {
                            if (dr["mode"].ToString().ToLower() == "enable")
                            {
                                bDelete = true;
                            }
                            else if (dr["mode"].ToString().ToLower() == "disable")
                            {
                                bDelete = false;
                            }
                            Delete_rowid = dr["message"].ToString();
                        }
                        break;
                    default:
                        break;
                }
            }
            dsTemp.Dispose();
            dsTemp = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getDelOverrideAccess : Error : " + ex.Message);
        }
    }

    private void getEditOverrideAccess(ref bool bEdit, String Page_id, string Object_Table_Name, ref String Edit_rowid)
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            DataSet dsTemp = HDD.GetDataset("select * from sy_object_access_override where object='" + Page_id + "' and action='edit' and active='1';");

            foreach (DataRow dr in dsTemp.Tables[0].Rows)
            {
                switch (dr["action"].ToString().ToLower())
                {
                    case "edit":
                        bool bRecord = getOverrideForThisRecord(dr["condition"].ToString());
                        if (bRecord)
                        {
                            if (dr["mode"].ToString().ToLower() == "enable")
                            {
                                bEdit = true;
                            }
                            else if (dr["mode"].ToString().ToLower() == "disable")
                            {
                                bEdit = false;
                            }
                            Edit_rowid = dr["af_row_id"].ToString();
                        }
                        break;
                    default:
                        break;
                }
            }
            dsTemp.Dispose();
            dsTemp = null;
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getEditOverrideAccess : Error : " + ex.Message);
        }
    }

    private bool getOverrideForThisRecord(String Condition)
    {
        bool bRet = true;
        try
        {
            HDDatabase HDD = new HDDatabase();
            String sSql = "select af_row_id from " + dsePageInfo.Tables["page"].Rows[0]["page_table_name"].ToString() + " where af_row_id='" + Request.QueryString["PK"] + "'";
            if (Condition != "")
            {
                sSql = "select af_row_id from " + dsePageInfo.Tables["page"].Rows[0]["page_table_name"].ToString() + " where af_row_id='" + Request.QueryString["PK"] + "' and " + Condition;
            }
            String sRet = HDD.GetColumnValue(sSql);

            if (sRet != "")
            {
                bRet = true;
            }
            else
            {
                bRet = false;
            }
        }

        catch (Exception ex)
        {
            LogWriter.WriteLog("getOverrideForThisRecord : Error : " + ex.Message);
        }

        return bRet;
    }


    // Added by srivatsan on Sep 29 2009 for Notes changes
    // This will Create the notes section and render onto td_dynamic_notes Tablecell
    private void AddNotesSection(DataSet dsPageInfo)
    {
        try
        {
            if (Request.QueryString["CPY"] == null)
            {
                if (Request.QueryString["PK"] != null)
                {
                    if (dsPageInfo != null)
                    {
                        if (dsPageInfo.Tables["ObjectNotes"] != null)
                        {
                            if (dsPageInfo.Tables["ObjectNotes"].Rows.Count > 0)
                            {
                                bool canshownotes = Convert2Boolean(dsPageInfo.Tables["ObjectNotes"].Rows[0]["associate_notes"].ToString());
                                if (canshownotes)
                                {
                                    DynamicDisplayI DDI = new DynamicDisplayI();
                                    //DataTable dtChilds = DDI.getAllChildObjects(strPagesetRowId);
                                    DataTable dtChilds = GetNotesAsChildObject(strPagesetRowId, dsPageInfo);
                                    if (dtChilds != null)//implemenetd by sanal on April 03, 2008
                                        if (dtChilds.Rows.Count > 0)
                                        {
                                            DDI.getPagesetandLoad(dtChilds, frmObj);
                                            if (Request.QueryString["isDDE"] == null)//Added by srivatsan for DDE changes
                                                Navigator.storeURL(Request.Url.ToString(), IsPostBack, false, false);
                                        }
                                    DDI = null;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddNoteSection :" + ex.Message);
        }
        finally
        {
            
        }
    }

    // Added by srivatsan on Sep 29 2009 for Notes changes
    // This will create a temp Data Table with Notes as the Child page of the current page
    private DataTable GetNotesAsChildObject(string strPagesetRowId,DataSet dsPageInfo)
    {
        HDDatabase HDD = new HDDatabase();
        ScreenReader SR = new ScreenReader();
        DataTable dt = null;
        try
        {
            //string sql = "select * from sy_obj_mas_detail where 1=2";
           // dt = HDD.GetDataTable(sql);
            if (dsPageInfo.Tables["PageKeys"] != null)
            {
                dt = dsPageInfo.Tables["PageKeys"].Clone();
            }

            if (dt != null)
            {
                DataRow drr = dt.NewRow();
                if (drr != null)
                {
                    //drr.BeginEdit();
                    drr["af_row_id"] = SR.getHashKey();
                    drr["object_id"] = "6596621416b78835";
                    drr["attrib_id"] = "related_af_row_id";
                    drr["master_obj"] = dsPageInfo.Tables["Page"].Rows[0]["object_id"].ToString();
                    drr["display_att"] = "af_row_id";
                    drr["created_by"] = "e51e0327224a2eb9";
                    drr["created_at"] = DateTime.Now;
                    drr["modified_at"] = DateTime.Now;
                    drr["modified_by"] = "e51e0327224a2eb9";
                    drr["attrib_name"] = "Related Af row id";
                    drr["owner_id"] = "e51e0327224a2eb9";
                    //drr.AcceptChanges();

                    dt.Rows.Add(drr);
                    //dt.ImportRow(drr);
                    dt.AcceptChanges();
                }
            }
            
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : GetNotesAsChildObject : " + ex.Message);
        }
        finally
        {
            HDD = null;
            SR = null;
        }
        return dt;
    }

    private bool Convert2Boolean(string input)
    {
        bool status = false;
        try
        {
            if (input.Trim() != "")
            {
                status = Convert.ToBoolean(input);
            }
        }
        catch (Exception ex)
        {
            status = false;
        }
        finally
        {

        }
        return status;

    }
    //Added by srivatsan on Oct 07 2009
    // This will create additional sections for related records
    private void AddRelatedRecordsSections(DataSet dsPageInfo,string strPagesetRowID)
    {
        AdditionalPageInfo addinfo = new AdditionalPageInfo();
        try
        {
            if (Request.QueryString["PK"] != null)
            {
                addinfo.GenerateRelatedRecordsSections(dsPageInfo, strPagesetRowID, ref td_additional_related_records);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddRelatedRecordsSections: " + ex.Message);
        }
        finally
        {
            addinfo = null;
        }

    }

    private void UpdateActionButton(DataSet dsePageInfo)
    {
        Action action = new Action();
        try
        {
            
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] == null)
                {
                    if (dsePageInfo != null)
                        if (dsePageInfo.Tables.Count > 0)
                            if (dsePageInfo.Tables.Contains("Page Actions"))
                            {
                                DataRow[] drractions = dsePageInfo.Tables["Page Actions"].Select();
                                if (drractions.Length > 0)
                                {
                                    HtmlTableCell htc = (HtmlTableCell)Form.FindControl("td_action_div");
                                    HtmlTableCell htcheader = (HtmlTableCell)Form.FindControl("td_action");
                                    action.CreateActionImage("img_action_header", ref htcheader);
                                    action.CreateActionDIV(ref htc, drractions, "img_action_header", Request.QueryString["PK"].ToString(), true);
                                }
                            }
                }
            }
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : UpdateActionButton : "+ ex.Message);
        }
        finally
        {
            action = null;
        }
    }

    private void SetDefaultButton()
    {
        if (btnSave.Visible == true)
        {
            Page.Form.DefaultButton = btnSave.UniqueID;
            Page.Form.DefaultFocus = btnSave.UniqueID;
        }
        else if (btnUpdate.Visible == true)
        {
            Page.Form.DefaultButton = btnUpdate.UniqueID;
            Page.Form.DefaultFocus = btnUpdate.UniqueID;
        }
    }

    /// <summary>
    ///  This function will Hide Side panels and menus when the page is lookup from DDE
    /// </summary>
    private void HideControlsForDEE()
    {
        try
        {
            if (Request.QueryString["isDDE"] != null)
            {
                //if (Request.QueryString["isDDE"].ToString() == "1")
                //{
                    Control ctrl = this.Master.FindControl("ContentPlaceHolder1");
                    if (ctrl != null)
                    {
                        ctrl.Visible = false;
                    }
                    ctrl = this.Master.FindControl("ContentPlaceHolder2");
                    if (ctrl != null)
                    {
                        ctrl.Visible = false;
                    }
                    ctrl = this.Master.FindControl("td_CollapsePanel");
                    if (ctrl != null)
                    {
                        ctrl.Visible = false;
                    }
                    ctrl = this.Master.FindControl("td_accordian");
                    if (ctrl != null)
                    {
                        ctrl.Visible = false;
                    }
                    ctrl = this.Master.FindControl("td_MenuHeader");
                    if (ctrl != null)
                    {
                        ctrl.Visible = false;
                    }
                    ctrl = this.Master.FindControl("td_MenuHeader1");
                    if (ctrl != null)
                    {
                        ctrl.Visible = false;
                    }
                    ctrl = this.Master.FindControl("feedback_tr");
                    if (ctrl != null)
                    {
                        ctrl.Visible = false;
                    }
                    ctrl = this.Master.FindControl("ctl00_td_action");
                    if (ctrl != null)
                    {
                        ctrl.Visible = false;
                    }
                    ctrl = this.Master.FindControl("tbl_acc_hd");
                    if (ctrl != null)
                    {
                        ctrl.Visible = false;
                    }
                    ctrl = this.Master.FindControl("tbl_fb_hd");
                    if (ctrl != null)
                        ctrl.Visible = false;
                    ctrl = this.Master.FindControl("tr_menuHeader");
                    if (ctrl != null)
                        ctrl.Visible = false;
                    ctrl = this.Master.FindControl("tbl_hdr");
                    if (ctrl != null)
                        ctrl.Visible = false;
                    ctrl = this.Master.FindControl("CollapsiblePanelExtender1");
                    if (ctrl != null)
                    {
                        AjaxControlToolkit.CollapsiblePanelExtender colext = (AjaxControlToolkit.CollapsiblePanelExtender)ctrl;
                        colext.CollapseControlID = "";
                        colext.ExpandControlID = "";
                    }
                    ctrl = this.Master.FindControl("panel1");
                    if (ctrl != null)
                        ctrl.Visible = false;
                    td_additional_related_records.Visible = false;
                    td_dynamic_notes.Visible = false;
                    tdadditionalsections.Visible = false;
                    tdDisplayGrid.Visible = false;
                    ////ctrl = this.Master.FindControl("td_additional_related_records");
                    ////if(ctrl!=null)
                    ////    ctrl.Visible = false;
                    ////ctrl = this.Master.FindControl("td_dynamic_notes");
                    ////if(ctrl!=null)
                    ////    ctrl.Visible = false;
                    ////ctrl = this.Master.FindControl("tdadditionalsections");
                    ////if (ctrl != null)
                    ////    ctrl.Visible = false;
                    ////ctrl = this.Master.FindControl("tdDisplayGrid");
                    ////if (ctrl != null)
                    ////    ctrl.Visible = false;
                    ctrl = null;
                //}
            }

            HideSaveNextForDDE();
        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : HideControlsForDEE : "+ ex.Message);
        }
    }

    #region Old function For DDE save
    //private void AddEventForDDESave()
    //{
    //    DynamicDisplayI DDI = new DynamicDisplayI();
    //    try
    //    {
    //        //ArrayList list = GetDDEFields(dsePageInfo);
    //        //string strDDEFields = GetDDEFields(dsePageInfo);
    //        //if (strDDEFields.Trim() != "")
    //        //{
    //        //    DDI.setAttribute(btnSave.Attributes, "onClick", "return CheckForDDEDefaultValues('" + strDDEFields + "');");
    //        //    DDI.setAttribute(btnUpdate.Attributes, "onClick", "return CheckForDDEDefaultValues('" + strDDEFields + "');");
    //        //    DDI.setAttribute(btnSaveNew.Attributes, "onClick", "return CheckForDDEDefaultValues('" + strDDEFields + "');");

    //        //}
    //        if (Request.QueryString["isDDE"] != null)
    //        {
    //            //this.frmObj.Attributes.Add("onBlur", "javascript:CheckForTopWindowFocus();");
    //            //Table1.Attributes.Add("onclick", "javascript:CheckForTopWindowFocus();");
    //            string storagefield = "";
    //            string displayfield = "";
    //            string pagemode = "";
    //            if (Request.QueryString["SF"] != null) // ID of the field in pop up window which has the Storage value of bind
    //                storagefield = Request.QueryString["SF"].ToString();
    //            if (Request.QueryString["DF"] != null)// ID of the field in pop up window which has the Display value of bind
    //                displayfield = Request.QueryString["DF"].ToString();


    //            if (Request.QueryString["PK"] != null)
    //                pagemode = "EDT";
    //            else
    //                pagemode = "ADD";


    //            DDI.setAttribute(btnSave.Attributes, "onClick", "javascript:SetValueForDDE('" + Request.QueryString["isDDE"].ToString() + "','" + storagefield + "','" + displayfield + "','" + pagemode + "');");//window.close();
    //            DDI.setAttribute(btnUpdate.Attributes, "onClick", "javascript:SetValueForDDE('" + Request.QueryString["isDDE"].ToString() + "','" + storagefield + "','" + displayfield + "','" + pagemode + "');");//window.close();
    //            DDI.setAttribute(btnSaveNew.Attributes, "onClick", "javascript:SetValueForDDE('" + Request.QueryString["isDDE"].ToString() + "','" + storagefield + "','" + displayfield + "','" + pagemode + "');");//window.close();

    //            Control con = DDI.FindControl(frmObj.Controls, "btnSaveTop"); // Header buttons
    //            Button btnobj = null;
    //            if (con != null)
    //            {
    //                btnobj = (Button)con;
    //                DDI.setAttribute(btnobj.Attributes, "onClick", "javascript:SetValueForDDE('" + Request.QueryString["isDDE"].ToString() + "','" + storagefield + "','" + displayfield + "','" + pagemode + "');disableThis('ctl00_ContentPlaceHolder3_btnSave','Saving...'); return false;");//window.close(); 
    //            }
    //            con = DDI.FindControl(frmObj.Controls, "btnSaveNewTop");
    //            if (con != null)
    //            {
    //                btnobj = (Button)con;
    //                DDI.setAttribute(btnobj.Attributes, "onClick", "javascript:SetValueForDDE('" + Request.QueryString["isDDE"].ToString() + "','" + storagefield + "','" + displayfield + "','" + pagemode + "');disableThis('ctl00_ContentPlaceHolder3_btnSaveNew','Saving...');");//window.close(); 
    //            }
    //            con = DDI.FindControl(frmObj.Controls, "btnUpdateTop");
    //            if (con != null)
    //            {
    //                btnobj = (Button)con;
    //                DDI.setAttribute(btnobj.Attributes, "onClick", "javascript:SetValueForDDE('" + Request.QueryString["isDDE"].ToString() + "','" + storagefield + "','" + displayfield + "','" + pagemode + "');disableThis('ctl00_ContentPlaceHolder3_btnUpdate','Saving...'); return false;");//window.close(); 
    //            }
    //            con = null;
    //            //DDI = null;
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        LogWriter.WriteLog("Error : AddEventForDDESave :" + ex.Message);
    //    }
    //    finally
    //    {
    //        DDI = null;
    //    }
    //}
    //private string GetDDEFields(DataSet dsePageInfo)
    //{
    //    ArrayList list = new ArrayList();
    //    string result = "";
    //    try
    //    {
    //        if (dsePageInfo != null)
    //            if (dsePageInfo.Tables.Count > 0)
    //                if (dsePageInfo.Tables["PageCtrl"] != null)
    //                    if (dsePageInfo.Tables["PageCtrl"].Rows.Count > 0)
    //                    {
    //                        string page_id = dsePageInfo.Tables["Page"].Rows[0]["page_id"].ToString();
    //                        DataRow[] drr = dsePageInfo.Tables["PageCtrl"].Select("control_html='DDE' and control_visible = 1");
    //                        if (drr.Length > 0)
    //                        {
    //                            for (int i = 0; i < drr.Length; i++)
    //                            {
    //                                //list.Add(page_id + "_" + drr[i]["control_id"].ToString());
    //                                result = result + "|" + page_id + "_" + drr[i]["control_id"].ToString() +"~"+drr[i]["control_name"].ToString();
    //                            }
    //                        }
    //                    }
    //    }
    //    catch(Exception ex)
    //    {
    //        LogWriter.WriteLog("Error : GetDDEFields : "+ ex.Message);
    //    }

    //    //return list;
    //    return result;

    //}
    #endregion


    /// <summary>
    /// This function will Hide the Save & Next button when DDE is used in Add or copy mode
    /// </summary>
    private void HideSaveNextForDDE()
    {
        DynamicDisplayI DDI = null;
        try
        {
            if (Request.QueryString["isDDE"] != null)
            {
                if (Request.QueryString["PK"] == null || Request.QueryString["CPY"] != null)
                {
                    DDI = new DynamicDisplayI();
                    btnSaveNew.Visible = false;
                    Control con = DDI.FindControl(this.Form.Controls, "btnSaveNewTop");
                    if (con != null)
                    {
                        Button btn = (Button)con;
                        btn.Visible = false;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : HideSaveNextForDDE : " + ex.Message);
        }
        finally
        {
            DDI = null;
        }
    }

    /// <summary>
    /// This function is used to set value for DDE control in Top(master) page after save or edit is successfull
    /// </summary>
    private void SetValueForDDE()
    {
        try
        {
            string storagefield = "";
            string displayfield = "";
            string pagemode = "";
            if (Request.QueryString["SF"] != null) // ID of the field in pop up window which has the Storage value of bind
                storagefield = Request.QueryString["SF"].ToString();
            if (Request.QueryString["DF"] != null)// ID of the field in pop up window which has the Display value of bind
                displayfield = Request.QueryString["DF"].ToString();


            if (Request.QueryString["PK"] != null)
                pagemode = "EDT";
            else
                pagemode = "ADD";

            string startupScript = "<script language=\"javascript\">SetValueForDDE('" + Request.QueryString["isDDE"].ToString() + "','" + storagefield + "','" + displayfield + "','" + pagemode + "');</script>";
            Page.ClientScript.RegisterStartupScript(this.Page.GetType(), "SetValueForDDE", startupScript);

        }
        catch(Exception ex)
        {
            LogWriter.WriteLog("Error : SetValueForDDE :"+ ex.Message);
        }
    }
    // Added by 'Imran Gani' on Sep 18 2012 for Documents changes
    /// <summary>
    /// This will Create the documents section and render onto td_dynamic_documents Tablecell
    /// </summary>
    /// <param name="dsPageInfo">Dataset about the page.</param>
    private void AddDocumentsSection(DataSet dsPageInfo)
    {
        try
        {
            if (Request.QueryString["CPY"] == null)
            {
                if (Request.QueryString["PK"] != null)
                {
                    if (dsPageInfo != null)
                    {
                        if (dsPageInfo.Tables["ObjectNotes"] != null)
                        {
                            if (dsPageInfo.Tables["ObjectNotes"].Rows.Count > 0)
                            {
                                bool canshownotes = Convert2Boolean(dsPageInfo.Tables["ObjectNotes"].Rows[0]["associate_documents"].ToString());
                                if (canshownotes)
                                {
                                    DynamicDisplayI DDI = new DynamicDisplayI();
                                    DataTable dtChilds = GetDocumentsAsChildObject(strPagesetRowId, dsPageInfo);
                                    if (dtChilds != null)
                                        if (dtChilds.Rows.Count > 0)
                                        {
                                            DDI.getPagesetandLoad(dtChilds, frmObj);
                                            if (Request.QueryString["isDDE"] == null)
                                                Navigator.storeURL(Request.Url.ToString(), IsPostBack, false, false);
                                        }
                                    DDI = null;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddDocumentsSection :" + ex.Message);
        }
        finally
        {
        }
    }

    // Added by 'Imran Gani' on Sep 18 2012 for Documents changes
    /// <summary>
    /// This will create a temp Data Table with Documents details as the Child page of the current page
    /// </summary>
    /// <param name="strPagesetRowId">Current page set ID</param>
    /// <param name="dsPageInfo">Dataset of the current page</param>
    /// <returns>DataTable for documents child</returns>
    private DataTable GetDocumentsAsChildObject(string strPagesetRowId, DataSet dsPageInfo)
    {
        HDDatabase HDD = new HDDatabase();
        ScreenReader SR = new ScreenReader();
        DataTable dt = null;
        try
        {
            if (dsPageInfo.Tables["PageKeys"] != null)
                dt = dsPageInfo.Tables["PageKeys"].Clone();

            if (dt != null)
            {
                DataRow drr = dt.NewRow();
                if (drr != null)
                {
                    drr["af_row_id"] = SR.getHashKey();
                    drr["object_id"] = "7b0977c9e6ac9dea";
                    drr["attrib_id"] = "related_af_row_id";
                    drr["master_obj"] = dsPageInfo.Tables["Page"].Rows[0]["object_id"].ToString();
                    drr["display_att"] = "af_row_id";
                    drr["created_by"] = "e51e0327224a2eb9";
                    drr["created_at"] = DateTime.Now;
                    drr["modified_at"] = DateTime.Now;
                    drr["modified_by"] = "e51e0327224a2eb9";
                    drr["attrib_name"] = "Related Af row id";
                    drr["owner_id"] = "e51e0327224a2eb9";

                    dt.Rows.Add(drr);
                    dt.AcceptChanges();
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetDocumentsAsChildObject : " + ex.Message);
        }
        finally
        {
            HDD = null;
            SR = null;
        }
        return dt;
    }

    // Added by 'Imran Gani' on 31-May-2013 to set the property for sections as tabs
    /// <summary>
    /// This will set the property for sections as tabs
    /// </summary>
    /// <param name="dsPageInfo">Dataset about the page details.</param>
    private void ShowSectionsAsTabs(DataSet dsPageInfo)
    {
        try
        {
            if (dsPageInfo != null)
                if (dsPageInfo.Tables["Page"] != null)
                    if (dsPageInfo.Tables["Page"].Rows.Count > 0)
                    {
                        bool isMultiRecords = Convert2Boolean(dsPageInfo.Tables["Page"].Rows[0]["multiple_recs_page"].ToString());
                        if (!isMultiRecords)
                            hfSectionsAsTabs.Value = dsPageInfo.Tables["Page"].Rows[0]["sections_as_tabs"].ToString();
                    }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : ShowSectionsAsTabs :" + ex.Message);
        }
    }

    /********* Added by 'Imran Gani' (copied from RakaTech) on 05-Sep-2013 for Task & Alerts *********/
    public void AddTaskSection(DataSet dsPageInfo)
    {
        try
        {
            if (Request.QueryString["CPY"] == null)
            {
                if (Request.QueryString["PK"] != null)
                {
                    if (dsPageInfo != null)
                    {
                        if (dsPageInfo.Tables["ObjectNotes"] != null)
                        {
                            if (dsPageInfo.Tables["ObjectNotes"].Rows.Count > 0)
                            {
                                bool canshowtask = Convert2Boolean(dsPageInfo.Tables["ObjectNotes"].Rows[0]["associate_task"].ToString());
                                if (canshowtask)
                                {
                                    DynamicDisplayI DDI = new DynamicDisplayI();
                                    DataTable dtChilds = DDI.getAllChildObjects(strPagesetRowId);
                                    dtChilds = GetTaskAsChildObject(strPagesetRowId, dsPageInfo);
                                    if (dtChilds != null)//implemenetd by sanal on April 03, 2008
                                        if (dtChilds.Rows.Count > 0)
                                        {
                                            DDI.getPagesetandLoad(dtChilds, frmObj);
                                            if (Request.QueryString["isDDE"] == null)//Added by srivatsan for DDE changes
                                                Navigator.storeURL(Request.Url.ToString(), IsPostBack, false, false);
                                        }
                                    DDI = null;
                                }
                            }
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddNoteSection :" + ex.Message);
        }
        finally
        {}
    }
    private DataTable GetTaskAsChildObject(string strPagesetRowId, DataSet dsPageInfo)
    {

        HDDatabase HDD = new HDDatabase();
        ScreenReader SR = new ScreenReader();
        DataTable dt = null;
        try
        {
            //string sql = "select * from sy_obj_mas_detail where 1=2";
            // dt = HDD.GetDataTable(sql);
            if (dsPageInfo.Tables["PageKeys"] != null)
            {
                dt = dsPageInfo.Tables["PageKeys"].Clone();
            }

            if (dt != null)
            {
                DataRow drr = dt.NewRow();
                if (drr != null)
                {
                    //drr.BeginEdit();
                    drr["af_row_id"] = SR.getHashKey();
                    drr["object_id"] = "e1ecbe37624d00e0";
                    drr["attrib_id"] = "related_af_row_id";
                    drr["master_obj"] = dsPageInfo.Tables["Page"].Rows[0]["object_id"].ToString();
                    drr["display_att"] = "af_row_id";
                    drr["created_by"] = Session["user_afrowid"].ToString();
                    drr["created_at"] = DateTime.Now.ToUniversalTime();
                    drr["modified_at"] = DateTime.Now.ToUniversalTime();
                    drr["modified_by"] = Session["user_afrowid"].ToString();
                    drr["attrib_name"] = "Related Af row id";
                    drr["owner_id"] = Session["user_afrowid"].ToString();
                    //drr.AcceptChanges();

                    dt.Rows.Add(drr);
                    //dt.ImportRow(drr);
                    dt.AcceptChanges();
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : GetTaskAsChildObject : " + ex.Message);
        }
        finally
        {
            HDD = null;
            SR = null;
        }
        return dt;
    }
    /********* End of Task & Alerts *********/
}
